
import re
import os
from datetime import datetime
from util import send_data_to_mqtt
from setting import logger

from db_function import DataBaseFunction

class SyncNotSubmitted:

    def get_last_info_time(self) -> int:
        '''return : 1698772748
        '''

        with open("/var/log/receive_ns_task.log", "rb") as file:
            file.seek(-2000, 2)  # 从文件末尾前推1000个字节的位置开始读取
            last_1000_chars = file.read().decode('utf-8')

        logger.info("last_1000_chars:")
        logger.info(last_1000_chars)

        regex = "'datetime': '(.*?)', 'datr':"

        datetime_str_list = re.findall(regex, last_1000_chars)

        if not datetime_str_list:

            return None
        
        datetime_str = datetime_str_list[-1]

        time_format = "%Y-%m-%dT%H:%M:%SZ"

        # 将时间字符串转换为datetime对象
        dt = datetime.strptime(datetime_str, time_format)

        # 将datetime对象转换为时间戳
        timestamp = int(dt.timestamp()) - 8*3600

        return timestamp
    

    def send_task(self):
        '''下发同步任务'''

        exists = os.path.isfile("/var/log/receive_ns_task.log")

        if not exists:

            return

        timestamp = self.get_last_info_time()

        logger.info(f"syn time point:{timestamp}")

        if not timestamp:

            return

        with DataBaseFunction() as df:

            base_station_info = df.get_base_staion_info()

            for i in base_station_info:

                data = {"task_type": "sync_not_submitted",  "data": {"timestamp": timestamp}}

                send_data_to_mqtt(data, topic = f"{i['mac']}_transcations")

                logger.info("下发同步任务：" + f"{i['mac']}_transcations")
                logger.info(data)

                





